#include "baseport.h"
#include <QDebug>
#include <QElapsedTimer>

BasePort::BasePort(QObject *parent)
    : QObject (parent)
{
    m_mutex = new QMutex(QMutex::Recursive);
    m_timer = new QTimer(this);
    m_timer->setInterval(1000);
    connect(m_timer, &QTimer::timeout, this, &BasePort::on1sTimeout);
    m_statistics = new PortStatistics(this);
}

BasePort::~BasePort()
{
    delete m_statistics;
    delete m_mutex;
    if (m_finder)
        m_finder->deleteLater();
}

void BasePort::setName(QString name)
{
    QMutexLocker locker(m_mutex);
    m_name = name;
}

QString &BasePort::getName()
{
    QMutexLocker locker(m_mutex);
    return m_name;
}

void BasePort::setID(PortID id)
{
    QMutexLocker locker(m_mutex);
    m_id = id;
}

PortID BasePort::getID() const
{
    QMutexLocker locker(m_mutex);
    return m_id;
}

void BasePort::setMagic(uint magic)
{
    m_magic = magic;
}

uint BasePort::getMagic()
{
    QMutexLocker locker(m_mutex);
//    return m_magic;
    return (uint)m_id;
}

void BasePort::setFinder(BaseFindPacket *finder)
{
    QMutexLocker locker(m_mutex);
    if (m_finder)
    {
        m_finder->deleteLater();
    }
    m_finder = finder;
    m_finder->setStatistics(*m_statistics);
    m_finder->moveToThread(thread());
}

bool BasePort::waitForFinished(int timeout_ms)
{
    QElapsedTimer timer;
    timer.start();
    while (1)
    {
        if (m_syncFlag)
            return true;

        if (timer.hasExpired(timeout_ms))
        {
            m_syncFlag = true;
            return false;
        }
    }
}

void BasePort::start(void)
{
    open();
}

PortStatistics *BasePort::getPortStatistics() const
{
    QMutexLocker locker(m_mutex);
    return m_statistics;
}

void BasePort::onSend(const QByteArray &ba)
{
    QMutexLocker locker(m_mutex);
//    qDebug() << "send : " << ba;
    qint32 bytes = write(ba);
    if (bytes > 0)
    {
        m_statistics->sendBytes(bytes);
    }
}

void BasePort::on1sTimeout()
{
    QMutexLocker locker(m_mutex);
    m_statistics->on1sTimeout();
}
